<!DOCTYPE html>
<html>

  <head>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  </head>

  <body>
    <script type="text/javascript" src="/common/js/provider_configs.js"></script>
    <script type="text/javascript">
      const urlParams = new URLSearchParams(window.location.search);
      const authCode = urlParams.get('code');
      const state = urlParams.get('state');

      const stateMessage = {
        type: 'state',
        state
      }
      window.opener.postMessage(stateMessage, "*");

      const onMainWindowMessageFn = (e) => {
        if (!e.data.codeVerifier) { return };
        const { TOKEN_URI,
          CLIENT_ID,
          CONFIGURED_REDIRECT_URIS: { SIMPLE: redirectUri },
          AUDIENCE } = PROVIDER_CONFIGS.AUTH0;
        const tokenRequestBody = {
          grant_type: 'authorization_code',
          redirect_uri: redirectUri,
          code: authCode,
          code_verifier: e.data.codeVerifier,
          client_id: CLIENT_ID,
          audience: AUDIENCE
        }
        var headers = {
          'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
        axios.post(TOKEN_URI, new URLSearchParams(tokenRequestBody), { headers })
          .then((response) => {
            const accessToken = response.data.access_token;
            const tokenMessage = {
              type: 'accessToken',
              accessToken
            }
            window.opener.postMessage(tokenMessage, "*");
            window.close();
          }
          );
      }
      window.addEventListener('message', onMainWindowMessageFn, false);
    </script>
  </body>

</html>